# -*- coding: utf-8 -*-
"""
@Time : 2023/6/11 21:43
@Author : Gremore
@File : calendar_api
@Des: 
"""

from tsim.routers.plan.request_model import CreateCalendarBody, UpdateCalendarBody, DeleteCalendarBody
from tsim.commons.responses.response_model import ResponseDto, ListResponseDto
from tsim.models import Session
from tsim.models.calendar import CalendarTab
from tsim.core.Response import success, fail
from fastapi import Request, Query, APIRouter, Security, File, UploadFile, Depends
from tsim.commons.utils import typetransfer
from tsim.models import get_db

calendar_router = APIRouter(prefix="/calendar")

@calendar_router.get("", summary="日历查询")
async def calendar_list(page: int = 1, perPage: int = 10, search: str = None):
    session = Session()
    model = CalendarTab
    # like 比较特殊，必须f"%{search}%" if search else None
    result = session.query(model).all()
    print("result:", result)
    # result = result.get("start_time")
    data = {
        "schedules": result
    }
    return success(data=data, msg='查询成功')

@calendar_router.post("/create", summary="日历创建")
async def calendar_create(body: CreateCalendarBody, db: Session = Depends(get_db)):
    model = CalendarTab
    plan = model(body)
    db.add(plan)
    print("请求修改：", plan)
    db.commit()  # 最后需要调用commit()方法提交事务
    return ResponseDto(msg="添加成功")


@calendar_router.post("/update", summary="计划修改")
async def calendar_update(body: UpdateCalendarBody, db: Session = Depends(get_db)):
    """
    更新信息
    :param body:
    :param db:
    :return:
    """
    model = CalendarTab

    check = db.query(model).filter(model.id == body.id).first()
    if not check:
        return fail(msg="id不存在")
    # check = db.commit
    print("请求修改：check", check)

    # items = typetransfer.convert_to_dict(body)
    # print("请求修改：", items)
    # print("请求修改：", body)
    # plan = model(body)
    # print("请求修改：", plan)
    db.query(model).filter(model.id == body.id).update({'title': "Jack",'start_time':body.start_time})
    db.commit()
    return success(msg="更新成功!")


@calendar_router.delete("/delete", summary="计划删除")
async def calendar_delete(request: Request, body: DeleteCalendarBody,
                          db: Session = Depends(get_db)):
    """
    删除
    :param request
    :param body
    :param db
    :return:
    """
    if request.method == "DELETE":
        print("请求修改：", body)
        model = CalendarTab
        result = db.query(model).filter(model.id == body.id).first()
        db.delete(result)  # 删除数据
        db.commit()  # 提交事务

        return success(msg="删除成功")
    return fail(msg="失败")